Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

For - Each Loop

For-Each in java

For-Each

A for-each loop is a special type of loop that is used to iterate over a collection of elements. The for-each loop has two parts: The iterable: This is the collection of elements that you want to iterate over. The body: This is the block of code that you want to execute for each element in the collection. Here is the syntax for the for-each loop:
for-each syntax
for (element : iterable) { // block of code }
The element variable is a temporary variable that is used to store each element in the collection. The iterable variable is a reference to the collection of elements. The block of code is executed for each element in the collection. The order in which the elements are iterated over is determined by the order of the elements in the collection. Here is an example of a for-each loop:
For-each basic example
public class Main{ public static void main(String[] args){ String[] names = {"John", "Mary", "Peter"}; for (String name : names) { System.out.println(name); } } }

Output

John Mary Peter
In this example, the for-each loop will print the names in the array names to the console. The names variable is the iterable, and the name variable is the temporary variable. The block of code in this example is the statement System.out.println(name);. This statement prints the value of name to the console. The for-each loop is a concise and efficient way to iterate over a collection of elements. It is a good choice when you do not need to modify the collection of elements. Here are some additional things to keep in mind about for-each loops: The iterable can be any collection of elements, such as an array, a list, or a set. The temporary variable is only available within the scope of the for-each loop. The for-each loop cannot be nested.

  📌TAGS

★loop ★looping statement ★control statement ★control in java ★loops in java ★for ★while ★do while ★for each

Tutorials